package cn.itcast.SellTicekts;
//同步代码块解决多线成问题
public class SellTicektThread_05 implements Runnable {
    //定义变量
    private int ticekts  = 100;
    //定义一个锁
    private Object object = new Object();
    //重写run方法
    public void run(){
        //循环持续出票
        while (true){
            //给线程加锁
            synchronized(object){
                //判断是否有票
                if(ticekts>0){
                    //模拟延迟
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //有票输出窗口+票数
                    System.out.println(Thread.currentThread().getName()+"正在出第"+ticekts+"张票");
                    //票数自减
                    ticekts--;
                }else {
                    break;
                }
            }

        }
    }
    //同步方法解决多线程问题,讲线程方案放入synchronized修饰的自定义方法中，上面调用即可。
    public synchronized void sell(){
        while (true) {
            //判断是否有票
            if (ticekts > 0) {
                //模拟延迟
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //有票输出窗口+票数
                System.out.println(Thread.currentThread().getName() + "正在出第" + ticekts + "张票");
                //票数自减
                ticekts--;
            }
        }
    }
}
